const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const axios = require('axios');

// 配置参数
const CONFIG = {
  PRIVATE_KEY: 'kmSFc9xNkt2yhkwkm', // 签名密钥
  CHANNEL_CODE: '12646114', // 渠道编码
  API_ID: '1234567890123667035', // 接口ID
  BASE_URL: 'https://test-szsh.cmicrwx.cn/', // 测试环境地址
  PROD_URL: 'https://qy.cmicvip.cn/' // 生产环境地址
};

/**
 * 权益核销状态回传
 */
async function pushClearanceStatus(params) {
  try {
    // 1. 准备请求数据
    const transactionId = `CLR${Date.now()}`;
    const reqTime = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 17);
    
    const requestBody = {
      orderItemId: params.orderItemId,
      equityOrderId: params.equityOrderId || params.orderItemId,
      serverNum: params.serverNum,
      skuCode: params.skuCode,
      skuName: params.skuName || '',
      extCode: params.extCode || '',
      equityGrantTime: params.equityGrantTime || reqTime,
      couponId: params.couponId || '',
      clearanceTime: params.clearanceTime || reqTime,
      clearanceResult: params.clearanceResult,
      recoId: params.recoId || params.equityOrderId || params.orderItemId,
      verificationCancelFlag: params.verificationCancelFlag || 0
    };
    // 1. 将body按键名自然排序
  const sortedBody = {};
  Object.keys(requestBody)
    .sort()
    .forEach(key => {
      sortedBody[key] = requestBody[key];
    });
  
  // 2. 将排序后的body转为紧凑JSON字符串
  const bodyString = JSON.stringify(sortedBody).replace(/\s+/g, '');
    
    // 2. 生成签名
    const signStr = transactionId + reqTime + CONFIG.PRIVATE_KEY + bodyString;
    console.log('签名前字符串:', signStr);

    const sign = crypto.createHash('md5').update(signStr).digest('hex').toUpperCase();
    console.log('生成签名:', sign);
    
    // 3. 构建请求数据
    const requestData = {
      contractRoot: {
        head: {
          apiId: CONFIG.API_ID,
          channelCode: CONFIG.CHANNEL_CODE,
          transactionId,
          reqTime,
          sign,
          version: '1.0'
        },
        body: requestBody
      }
    };
    console.log('请求数据:', requestData);
    
    // 4. 发送请求
    const response = await axios.post(
      `${CONFIG.PROD_URL}cmpp-api/external/cleared/commonEquityCleared`,
      requestData,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    console.log('响应数据:', response.data);
  } catch (error) {
    console.error('核销状态回传失败:', error);
    return {
      success: false,
      code: '9999',
      message: error.response?.data?.contractRoot?.body?.resultMsg || error.message,
      error: error.response?.data || error.message
    };
  }
}
module.exports = {
  router,
  pushClearanceStatus
};